package com.lcf.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.lcf.base.exception.SysException;
import com.lcf.system.dao.SysRoleMenuDao;
import com.lcf.system.dto.role.RoleMenuDTO;
import com.lcf.system.entity.SysMenu;
import com.lcf.system.entity.SysRole;
import com.lcf.system.entity.SysRoleMenu;
import com.lcf.system.enums.SysMenuUseEnum;
import com.lcf.system.enums.SysRoleEnum;
import com.lcf.system.manager.CacheManager;
import com.lcf.system.manager.SysRoleManager;
import com.lcf.system.service.SysRoleMenuService;
import com.lcf.system.vo.roleMenu.SysRoleMenuVO;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * 角色与菜单(SysRoleMenu)表服务实现类
 *
 * @author lcf
 * @since 2025-02-25 12:28:49
 */
@Service("sysRoleMenuService")
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuDao, SysRoleMenu> implements SysRoleMenuService {
    @Resource
    private SysRoleManager sysRoleManager;
    @Resource
    private CacheManager cacheManager;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setRoleMenu(long roleId, RoleMenuDTO roleMenu) {
        SysRole sysRole = sysRoleManager.checkId(roleId);
        if (SysRoleEnum.isSysRole(sysRole.getRoleCode())) {
            throw new SysException("内置角色不允许修改");
        }

        //删除旧的角色菜单数据
        Db.lambdaUpdate(SysRoleMenu.class).eq(SysRoleMenu::getRoleId, roleId).remove();

        if (CollectionUtil.isNotEmpty(roleMenu.getMenuIdList())) {
            List<SysRoleMenu> list = roleMenu.getMenuIdList().stream().map(x -> new SysRoleMenu(roleId, x)).toList();
            saveBatch(list);
        }

        //删除角色缓存
        cacheManager.delRoleCache(roleId);
    }

    @Override
    public List<SysRoleMenuVO> getRoleMenuList(long roleId) {
        SysRole sysRole = sysRoleManager.checkId(roleId);
        if (Objects.equals(sysRole.getRoleCode(), SysRoleEnum.ADMIN.getCode())) {
            List<Long> menuIdList = Db.lambdaQuery(SysMenu.class)
                    .eq(SysMenu::getMenuUse, SysMenuUseEnum.TENANT.getCode())
                    .list().stream()
                    .map(SysMenu::getId)
                    .toList();

            if (CollectionUtil.isEmpty(menuIdList)) {
                return Collections.emptyList();
            }

            return menuIdList.stream().map(SysRoleMenuVO::new).toList();
        }

        List<SysRoleMenu> list = lambdaQuery().eq(SysRoleMenu::getRoleId, roleId).list();

        return BeanUtil.copyToList(list, SysRoleMenuVO.class);
    }
}

